package cn.kgc.security.config;

import cn.kgc.security.handler.MyAuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return  new BCryptPasswordEncoder();
    }

    @Autowired
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 指定哪些资源需要认证，哪些不需要
        http.authorizeRequests().antMatchers("/user/login").permitAll()
            .anyRequest().authenticated();

        http.formLogin().loginPage("/user/login")// 指定登录页
            //.loginProcessingUrl("/user/login") // 处理登录请求的url
            .failureForwardUrl("/user/login")  // 认证失败后跳转页面
            .defaultSuccessUrl("/");            // 认证成功后跳转页面
            //.successHandler(myAuthenticationSuccessHandler);  // 自定义成功后的处理

        http.logout().logoutSuccessUrl("/user/login");//注销成功后跳转页面

        http.exceptionHandling().accessDeniedPage("/403"); // 无权限访问页面

        http.cors().disable().csrf().disable(); // 关闭跨站请求伪造开关
    }
}
